package com.sdg.server.rest;


import com.sdg.server.model.domain.User;
import com.sdg.server.model.request.LoginUserRequest;
import com.sdg.server.model.request.RegisterUserRequest;
import com.sdg.server.service.MyUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;

/**
 * 用于处理user 相关的操作
 */
@Controller
@RequestMapping("/rest/users")
public class UserRestApi {
    @Autowired
    private MyUserService myUserService;

    //1.需要提供用户注册功能(路径,处理的数据类型,请求的方法)
    @RequestMapping(value = "/register", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Model addUser(String username, String password, Model model) {
        if (myUserService.checkUserExist(username)) {
            model.addAttribute("success", false);
            model.addAttribute("message", " 用户名已经被注册！");
            return model;
        }
        model.addAttribute("success", myUserService.registerUser(new RegisterUserRequest(username, password)));
        return model;
    }

    //2.用户登录功能
    @RequestMapping(value = "/login", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Model login(String username, String password, Model model) {
        User user = myUserService.loginUser(new LoginUserRequest(username, password));
        model.addAttribute("success", user != null);
        model.addAttribute("user", user);
        return model;
    }


    //3.冷启动问题(需要能够添加用户能够偏爱的影片类别)
    @RequestMapping(value = "/pref", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Model addPrefGenres(@RequestParam("username") String username, @RequestParam("genres") String genres, Model model) {
        User user = myUserService.findByUsername(username);
        user.getPrefGenres().addAll(Arrays.asList(genres.split(",")));
        user.setFirst(false);
        //User 中的第一次发生变化
        model.addAttribute("success", myUserService.updateUser(user));
        return model;
    }
}